-module(ring2).
-export([start/1, send_msg/1, stop/0]).
-export([create_process/2]).

start(N) -> call({start, N}).
send_msg(Msg) -> call({send_msg, Msg}).
stop() -> call(stop).

call({start, N}) ->
    Pid = spawn(?MODULE, create_process, [1, N]),
    register(ring, Pid);
call({send_msg, Msg}) ->
    ring ! {ok, Msg};
call(stop) ->
    ring ! stop.
    
% 进程1创建进程2，进程2创建进程3，...，进程n-1创建进程n
create_process(I, N) when I< N ->
  Pid = spawn(?MODULE, create_process, [I+1, N]),
  send_loop(Pid);
create_process(I, N) when I==N ->
  send_loop(ring).

send_loop(Pid) ->
  receive
    {ok, Content} -> io:format("Pid:~p, Msg:~p~n", [self(), Content]),
		     timer:sleep(10000), % sleep 10 seconds
		     Pid ! {ok, Content},
                     send_loop(Pid);
    stop          -> ok
  end.
